<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// 首页设置  middleware(['web'])->
//Route::get('/', function() { return view('welcome'); });
//Route::get('/', 'App\Http\Controllers\Frontend\HomeController@index');


// 数据库
Route::match(
    ['post', 'get',],
    '/db/{action?}',
    function($action = 'index') {
        try{
            // 执行请求
            $file   = 'App\Http\Controllers\Test\DatabaseController';
            $file   = App::make($file);
            $result = $file->$action();

            return $result;
        } catch(Exception $e){
            return ['code' => 1, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        }
    }
)->where(['action' => '[0-9a-zA-Z-]+'])->name('db'); // 统一命令


// 前台页面
Route::match(
    ['get', 'post'],
    '/{controller?}/{action?}/{param1?}/{param2?}/{param3?}', // .html
    function($controller = '', $action = '', $param1 = '', $param2 = '', $param3 = '') {
        try{
            //$request = request();
            //$post    = $request->all();
            $post = [];

            // 各种情况下的参数组合
            // 与 $controller 和 $action 有关
            if($param1){
                $param1 = str_replace('.html', '', $param1);
            }
            if($param2){
                $param2 = str_replace('.html', '', $param2);
            }
            if($param3){
                $param3 = str_replace('.html', '', $param3);
            }
            if($action){
                $action = str_replace('.html', '', $action);
            }
            if($controller){
                $controller = str_replace('.html', '', $controller);
            }
            // 首页
            if(empty($controller) && empty($action)){
                // 重新定义控制器与方法
                $controller = 'home';
                $action     = 'index';
            }
            if($controller == 'home'){
                if($action == 'down-word'){
                    $post['date'] = $param1;
                }
            }
            // 参数
            $post['controller'] = $controller;
            $post['action']     = $action;

            // 控制器   中划线 => 驼峰式:大小写
            $controller = str_replace(' ', '', ucwords(str_replace('-', ' ', $controller)));
            $file       = 'App\Http\Controllers\Frontend\\'.$controller.'Controller';
            $action     = str_replace(' ', '', ucwords(str_replace('-', ' ', $action)));
            $action     = lcfirst($action);
            if(class_exists($file)){
                // 获取请求参数
                request()->merge($post);
                // 执行请求
                $file   = App::make($file);
                $result = $file->$action();

                return $result;
            } else{
                //die($file.'类不存在！！');
                // 直接展示模板
                $tpl_file = strtolower($controller).($action ? '/'.strtolower($action) : '');
                $tpl_file = (isMobile() ? 'wap/' : '').$tpl_file;

                return view($tpl_file);
            }
        } catch(Exception $e){
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
            //return view('404');
        }
    }
)->where(['controller' => '[0-9a-zA-Z-\.]+', 'action' => '[0-9a-zA-Z-\.]+'])->name('frontend'); // 统一命令

// 判断是否是手机端
function isMobile():bool
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if(isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
        return true;
    }

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if(isset ($_SERVER['HTTP_VIA'])){
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;// 找不到为flase,否则为TRUE
    }

    // 判断手机发送的客户端标志,兼容性有待提高
    if(isset ($_SERVER['HTTP_USER_AGENT'])){
        $clientkeywords = array(
            'mobile',
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if(preg_match("/(".implode('|', $clientkeywords).")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
            return true;
        }
    }

    if(isset ($_SERVER['HTTP_ACCEPT'])){ // 协议法，因为有可能不准确，放到最后判断
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
            return true;
        }
    }

    return false;
}
